package com.we.weauth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.we.weauth.entity.User;
import com.we.weauth.service.UserService;
import com.we.weauth.vo.LoginVo;
import com.we.wecommon.utils.JWTUtils;
import com.we.wecommon.utils.MD5Utils;
import com.we.wecommon.utils.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * (user)表控制层
 *
 * @author xxxxx
 */
@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("select")
    public R getById(String id) {
        return R.ok(userService.getById(id));
    }

    @GetMapping("list")
    public R list() {
        return R.ok(userService.list());
    }

    /**
     *  新增数据
     * @param user
     * @return
     */
    @PostMapping("add")
    public R add(@RequestBody User user) {
        user.setPassword(MD5Utils.generatemd5(user.getPassword()));
        if (!userService.save(user)){
            return R.failure();
        }
        return R.ok();
    }

    /**
     *  修改数据
     * @param user
     * @return
     */
    @PostMapping("update")
    public R update(@RequestBody User user) {
        if (!userService.updateById(user)) {
            return R.failure();
        }
        return R.ok();
    }

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo){
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("name",loginVo.getName());
        User one = userService.getOne(queryWrapper);
        if (one == null){
            return R.failure();
        }
        if (!MD5Utils.verify(loginVo.getPassword(),one.getPassword())){
            return R.failure();
        }
        // 登录成功生成jwt密钥
        String token = JWTUtils.generateToken(one.getId());
        System.out.println(token);
        return R.ok(token,one);
    }

    /**
     *  删除数据
     *
     * @param id
     * @return
     */
    @PostMapping("delete")
    public R delete(String id) {
        if (!userService.removeById(id)) {
            return R.failure();
        }
        return R.ok();
    }
}
